import * as formulaLib from "@formulajs/formulajs";
import * as customformula from "./CustomFunction";

export function useFuncCalcHook() {
  /**
   * 执行公式
   */
  const safeEvalFunction = (evalFunction: Function, formulaScope: any): any => {
    try {
      const result = evalFunction(formulaScope);
      // 如果结果是 undefined 或 null
      if (result === undefined || result === null) {
        return "";
      }
      // 如果result是对象 并且包含message excel 公式内部返回这个错误
      if (typeof result === "object" && result.message === "#N/A") {
        console.error("Formula evaluation error:", result);
        return "";
      }
      return result;
    } catch (error) {
      console.error("Formula evaluation error:", error);
      return "";
    }
  };

  const evalFormula = (modelVal: any, formula: string, isSubForm: boolean) => {
    try {
      if (!formula) {
        return;
      }
      if (!modelVal) {
        return;
      }
      let flag = false;
      // 寻找表达式的变量
      let modifiedFormula = formula.replace(/#{([^}]+)}/g, (match, p1) => {
        const value = handleValue(p1, modelVal[p1], modelVal, isSubForm);
        if (value !== null && value !== undefined) {
          flag = true;
          return value;
        }
        return match; // 如果找不到对应的数据，则保持原样
      });

      if (!flag) return;
      console.debug(modifiedFormula);

      // 创建一个包含所有公式函数的作用域
      const formulaScope = {
        ...formulaLib,
        ...customformula,
        // 添加其他需要的全局变量或函数
        Math,
        Number,
        String,
        Array,
        Date,
        JSON,
        Object,
        console,
        // 添加一些常用的工具函数
        parseInt,
        parseFloat,
        isNaN,
        isFinite
      };

      try {
        // 首先尝试作为表达式执行
        const evalFunction = new Function(
          "formulaScope",
          `
          with (formulaScope) {
            return ${modifiedFormula};
          }
        `
        );
        return safeEvalFunction(evalFunction, formulaScope);
      } catch (e) {
        // 如果作为表达式执行失败，尝试作为完整代码执行
        try {
          const evalFunction = new Function(
            "formulaScope",
            `
            with (formulaScope) {
              ${modifiedFormula}
            }
          `
          );
          return safeEvalFunction(evalFunction, formulaScope);
        } catch (e2) {
          console.error("Formula execution failed:", e2);
          return "";
        }
      }
    } catch (e) {
      console.debug(e);
    }
    return "#N/A";
  };

  const handleValue = (key: string, val: any, modelVal: any, isSubForm: boolean) => {
    if (key.startsWith("number")) {
      return val;
    } else if (key.startsWith("sub_form")) {
      return handleSubFormVal(key, val, modelVal, isSubForm);
    } else if (key.endsWith("score")) {
      return val;
    } else {
      // 如果是字符串
      if (typeof val === "string") {
        return `'${val}'`;
      } else if (typeof val === "object") {
        return JSON.stringify(val);
      }
      return val;
    }
  };

  const handleSubFormVal = (key: string, val: any, modelVal: any, isSubForm: boolean) => {
    // 截取子表单具体值
    const keys = key.split(",");
    const valueKey = keys[0];
    const subValueKey = keys[1];
    if (isSubForm) {
      return modelVal[subValueKey];
    } else {
      // 找到子表单的值
      const subFormVal = modelVal[valueKey];
      let sumVal: any = null;
      // 累加子表单数组每项的值
      if (subFormVal && subFormVal.length > 0) {
        subFormVal.forEach((item: any) => {
          if (!sumVal) {
            sumVal = item[subValueKey];
          } else {
            sumVal += item[subValueKey];
          }
        });
      }
      return sumVal;
    }
  };

  return {
    evalFormula
  };
}
